package com.godme.idea;

public class Queens {


    public static void testQueens(int size){
        setQueens(new int[size], getTrueArray(size), 0);
    }


    public static void setQueens(int[] queens, boolean[] isOk, int row) {
        if (row == queens.length) {
            printQueens(queens);
            return;
        }
        for (int i = 0; i < isOk.length; i++) {
            if(isOk[i]){
                queens[row] = i;
                setQueens(queens, nextOk(queens, row+1), row+1);
            }
        }
    }

    public static boolean[] nextOk(int[] queen, int row){
        int length = queen.length;
        boolean[] isOk = getTrueArray(length);
        int left, right, distance, loc;
        for(int index=0; index<row; index++){
            loc = queen[index];
            isOk[loc] = false;
            distance = row - index;
            left = loc - distance;
            if(left > -1){
                isOk[left] = false;
            }
            right = loc + distance;
            if(right < length){
                isOk[right] = false;
            }
        }
        return isOk;
    }

    public static boolean[] getTrueArray(int size){
        boolean[] ta = new boolean[size];
        for (int i = 0; i < size; i++) {
            ta[i] = true;
        }
        return ta;
    }

    private static void printQueens(int[] queens) {
        for (int queen : queens) {
            for (int j = 0; j < queens.length; j++) {
                if (queen == j) {
                    System.out.print("Q|\t");
                } else {
                    System.out.print("*|\t");
                }
            }
            System.out.println();
        }
        System.out.println("-----------------------");
    }

    public static void main(String[] args) {
        testQueens(8);
    }
}
